package com.example.night.service.ApiService;

import com.example.night.data.Influencer.InfluencerPackage;
import com.example.night.data.InfluencerCoins.InfluencerCoins;
import com.example.night.data.InfluencerCoins.MonthlyInfluencerStats;
import com.example.night.data.InfluencerOperationRecord.InfluencerOperationRecord;
import com.example.night.data.Order.OrderPackage;
import com.example.night.service.MysqlService.InfluencerMysqlService;
import com.example.night.service.MysqlService.InfluencerOperationRecordMysqlService;
import com.example.night.service.MysqlService.MonthlyInfluencerStatsMysqlService;
import jakarta.annotation.PostConstruct;
import net.sourceforge.pinyin4j.PinyinHelper;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.concurrent.*;

@Service
public class InfluencerService {
    private final InfluencerMysqlService influencerMysqlService;
    private final InfluencerOperationRecordMysqlService influencerOperationRecordMysqlService;
    private final OrderService orderService;
    private final MonthlyInfluencerStatsMysqlService monthlyInfluencerStatsMysqlService;

    private List<InfluencerPackage> registeredInfluencerPackages = new ArrayList<>();
    private List<InfluencerPackage> pendingInfluencerPackages = new ArrayList<>();
    private List<InfluencerOperationRecord> influencerOperationRecords = new ArrayList<>();

    public InfluencerService(InfluencerMysqlService influencerMysqlService, InfluencerOperationRecordMysqlService influencerOperationRecordMysqlService, OrderService orderService, MonthlyInfluencerStatsMysqlService monthlyInfluencerStatsMysqlService) {
        this.influencerMysqlService = influencerMysqlService;
        this.influencerOperationRecordMysqlService = influencerOperationRecordMysqlService;
        this.orderService = orderService;
        this.monthlyInfluencerStatsMysqlService = monthlyInfluencerStatsMysqlService;
    }

    @PostConstruct
    public void init() {
        registeredInfluencerPackages = influencerMysqlService.getAllRegisteredInfluencers();
        getPendingInfluencersFromMysql();
        influencerOperationRecords = influencerOperationRecordMysqlService.getNonRejectedRecords();
    }

    public void updateRegisteredInfluencerPackages() {
        registeredInfluencerPackages = influencerMysqlService.getAllRegisteredInfluencers();
    }

    public void saveRegisteredInfluencerPackages() {
        influencerMysqlService.saveInfluencers(registeredInfluencerPackages);
    }

    // 方法：将达人添加到待注册达人列表中
    public void addInfluencerToPendingList(InfluencerPackage influencerPackage) {
        if (influencerPackage == null || influencerPackage.getPhone() == null || influencerPackage.getPhone().isEmpty()) {
            return; // 如果达人信息不完整，则不添加
        }

        // 生成密码，密码规则同saveOrUpdateInfluencers方法
        String password = getPinyinInitials(influencerPackage.getName()) + "123456";
        influencerPackage.setPassword(password);

        // 将达人添加到待注册列表中
        pendingInfluencerPackages.add(influencerPackage);
    }

    public void addPendingInfluencers (List<InfluencerPackage> influencerPackages){
        for (InfluencerPackage influencerPackage : influencerPackages) {
            addInfluencerToPendingList(influencerPackage);
            saveRecord(influencerPackage, -1);
        }
    }

    public void getPendingInfluencersFromMysql() {
        List<InfluencerOperationRecord> influencerOperationRecordList = influencerOperationRecordMysqlService.getRejectedRecords();
        for (InfluencerOperationRecord record : influencerOperationRecordList) {
            InfluencerPackage influencerPackage = new InfluencerPackage();
            influencerPackage.setPhone(record.getPhone());
            influencerPackage.setName(record.getName());
            influencerPackage.setRoleType(record.getRoleType());
            influencerPackage.setWxId(record.getWxId());
            influencerPackage.setZfbId(record.getZfbId());
            influencerPackage.setPromoteId(record.getPromoteId());
            pendingInfluencerPackages.add(influencerPackage);
        }
    }
    // 获取待注册的达人列表
    public List<InfluencerPackage> getPendingInfluencers() {
        return pendingInfluencerPackages;
    }

    public void movePendingInfluencerToRegistered(String promoteId) {
        if (promoteId == null || promoteId.isEmpty()) {
            return; // 如果 promoteId 为空，直接返回
        }

        // 查找待注册达人
        InfluencerPackage targetInfluencerPackage = null;
        for (InfluencerPackage influencerPackage : pendingInfluencerPackages) {
            if (promoteId.equals(influencerPackage.getPromoteId())) {
                targetInfluencerPackage = influencerPackage;
                break;
            }
        }

        if (targetInfluencerPackage == null) {
            return; // 未找到对应的达人，直接返回
        }

        saveRecord(targetInfluencerPackage, 1);
        // 从待注册列表中移除
        pendingInfluencerPackages.remove(targetInfluencerPackage);

        // 存入数据库
        influencerMysqlService.saveInfluencersInfo(List.of(targetInfluencerPackage));

        // 添加到已注册列表
        registeredInfluencerPackages.add(targetInfluencerPackage);
    }

    public void rejectPendingInfluencer(String promoteId) {
        if (promoteId == null || promoteId.isEmpty()) {
            return; // 如果 promoteId 为空，直接返回
        }

        // 查找待注册达人
        InfluencerPackage targetInfluencerPackage = null;
        for (InfluencerPackage influencerPackage : pendingInfluencerPackages) {
            if (promoteId.equals(influencerPackage.getPromoteId())) {
                targetInfluencerPackage = influencerPackage;
                break;
            }
        }

        if (targetInfluencerPackage == null) {
            return; // 未找到对应的达人，直接返回
        }
        saveRecord(targetInfluencerPackage, 0);
        // 从待注册列表中移除
        pendingInfluencerPackages.remove(targetInfluencerPackage);
    }

    public void saveRecord(InfluencerPackage influencerPackage, int operation) {
        InfluencerOperationRecord record = new InfluencerOperationRecord();
        record.setPromoteId(influencerPackage.getPromoteId());
        record.setName(influencerPackage.getName());
        record.setPhone(influencerPackage.getPhone());
        record.setWxId(influencerPackage.getWxId());
        record.setZfbId(influencerPackage.getZfbId());
        record.setOperation(operation);
        if (operation != -1) {
            influencerOperationRecords.add(record);
        }
        influencerOperationRecordMysqlService.saveOperation(record);
    }
    public List<InfluencerOperationRecord> getPendingInfluencerOperationRecords() {
        return influencerOperationRecords;
    }
    public void saveOrUpdateInfluencers(List<InfluencerPackage> influencerPackages) {
        if (influencerPackages == null || influencerPackages.isEmpty()) {
            return;
        }

        influencerMysqlService.saveInfluencersInfo(influencerPackages);

        for (InfluencerPackage influencerPackage : influencerPackages) {
            String password = getPinyinInitials(influencerPackage.getName()) + "123456";
            System.out.println(influencerPackage.getPhone());
            if (influencerPackage.getPhone() != null && !influencerPackage.getPhone().isEmpty()) {
                influencerPackage.setPassword(password);
                // 检查手机号是否已存在
                int existingIndex = -1;
                for (int i = 0; i < registeredInfluencerPackages.size(); i++) {
                    if (registeredInfluencerPackages.get(i).getPromoteId().equals(influencerPackage.getPromoteId())) {
                        existingIndex = i;
                        break;
                    }
                }

                if (existingIndex != -1) {
                    // 如果手机号已存在，则更新信息
                    registeredInfluencerPackages.set(existingIndex, influencerPackage);
                } else {
                    // 如果手机号不存在，则添加到列表
                    registeredInfluencerPackages.add(influencerPackage);
                }
            }
        }
    }


    // 获取已注册的达人列表
    public List<InfluencerPackage> getRegisteredInfluencers() {
        return registeredInfluencerPackages;
    }

    public List<InfluencerPackage> findInfluencersByPhone(String phone) {
        if (phone == null || phone.isEmpty()) {
            return List.of(); // 直接返回空列表
        }

        List<InfluencerPackage> matchedInfluencers = new ArrayList<>();
        for (InfluencerPackage influencer : registeredInfluencerPackages) {
            if (phone.equals(influencer.getPhone())) {
                matchedInfluencers.add(influencer);
            }
        }
        return matchedInfluencers;
    }
    public static String getPinyinInitials(String chinese) {
        StringBuilder initials = new StringBuilder();
        for (char c : chinese.toCharArray()) {
            String[] pinyinArray = PinyinHelper.toHanyuPinyinStringArray(c);
            if (pinyinArray != null) {
                initials.append(pinyinArray[0].charAt(0));
            }
        }
        return initials.toString().toUpperCase();
    }

    public void updateInfluencerByPromoteId(String promoteId) {
        InfluencerPackage influencerPackage = influencerMysqlService.findInfluencerByPromoteId(promoteId);
        if (influencerPackage != null) {
            // 更新 registeredInfluencers 列表
            for (int i = 0; i < registeredInfluencerPackages.size(); i++) {
                if (registeredInfluencerPackages.get(i).getPromoteId().equals(promoteId)) {
                    registeredInfluencerPackages.set(i, influencerPackage);
                    return;
                }
            }
            // 如果列表中没有该达人，则添加进去
            registeredInfluencerPackages.add(influencerPackage);
        }
    }

    public boolean validateLogin(String phone, String password) {
        if (phone == null || password == null) {
            return false;
        }

        for (InfluencerPackage influencerPackage : registeredInfluencerPackages) {
            if (phone.equals(influencerPackage.getPhone()) && password.equals(influencerPackage.getPassword())) {
                return true; // 登录成功
            }
        }
        return false; // 登录失败
    }
    public static String[] getLastMonthDateRange() {
        // 创建日历实例并设置为当前日期
        Calendar calendar = Calendar.getInstance();

        // 获取上个月
        calendar.add(Calendar.MONTH, -1);

        // 设置为上个月的第一天
        calendar.set(Calendar.DAY_OF_MONTH, 1);
        String startDate = new SimpleDateFormat("yyyy-MM-dd").format(calendar.getTime());

        // 设置为上个月的最后一天
        calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
        String endDate = new SimpleDateFormat("yyyy-MM-dd").format(calendar.getTime());

        return new String[]{startDate, endDate};
    }
    public static String getLastMonthDate() {
        // 创建日历实例并设置为当前日期
        Calendar calendar = Calendar.getInstance();

        // 获取上个月
        calendar.add(Calendar.MONTH, -1);

        // 设置为上个月的第一天
        calendar.set(Calendar.DAY_OF_MONTH, 1);
        String startDate = new SimpleDateFormat("yyyy-MM").format(calendar.getTime());

        return startDate;
    }
    public void getLastMonthInfluencersData() throws ParseException {
        String[] lastMonthDateRange = getLastMonthDateRange();

        // 使用线程池来并行处理每个 influencerPackage
        ExecutorService executorService = Executors.newFixedThreadPool(10); // 创建线程池，最多10个线程
        List<Callable<MonthlyInfluencerStats>> tasks = new ArrayList<>();

        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM");

        Date date = formatter.parse(getLastMonthDate());

        for (InfluencerPackage influencerPackage : registeredInfluencerPackages) {
            tasks.add(() -> {
                // 每个任务处理一个 influencerPackage
                influencerPackage.setOrderList(orderService.getOrders(lastMonthDateRange[0], lastMonthDateRange[1], influencerPackage.getPromoteId()));
                int totalOrders = influencerPackage.getOrderList().size();
                double totalGMV = 0.0;
                double commission = 0.0;
                int coins = 0;
                double leaderSysServiceMoney = 0.0;

                for (OrderPackage orderPackage : influencerPackage.getOrderList()) {
                    if (orderPackage.getStatus() != 3) {
                        totalGMV += orderPackage.getSysSettleMoney();
                        leaderSysServiceMoney += orderPackage.getSysRelateServiceMoneyIn();
                        commission += 0.0;
                    }

                }

                coins = (int) (leaderSysServiceMoney * 45);
                MonthlyInfluencerStats monthlyInfluencerStats = new MonthlyInfluencerStats();

                monthlyInfluencerStats.setCoins(coins);
                monthlyInfluencerStats.setLeaderSysServiceMoney(BigDecimal.valueOf(leaderSysServiceMoney));
                monthlyInfluencerStats.setTotalOrders(totalOrders);
                monthlyInfluencerStats.setTotalGMV(BigDecimal.valueOf(totalGMV));
                monthlyInfluencerStats.setName(influencerPackage.getName());
                monthlyInfluencerStats.setPromoteId(influencerPackage.getPromoteId());
                monthlyInfluencerStats.setPromoteName(influencerPackage.getPromoteName());
                monthlyInfluencerStats.setPhone(influencerPackage.getPhone());
                monthlyInfluencerStats.setTotalCommission(BigDecimal.valueOf(commission));
                monthlyInfluencerStats.setDate(date);

                return monthlyInfluencerStats;
            });
        }

        // 提交所有任务并等待结果
        try {
            List<Future<MonthlyInfluencerStats>> futures = executorService.invokeAll(tasks);
            List<MonthlyInfluencerStats> monthlyInfluencerStatss = new ArrayList<>();

            // 收集结果
            for (Future<MonthlyInfluencerStats> future : futures) {
                monthlyInfluencerStatss.add(future.get());
            }

            // 批量插入或更新
            monthlyInfluencerStatsMysqlService.addOrUpdateMonthlyStatsBatch(monthlyInfluencerStatss);

        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        } finally {
            // 关闭线程池
            executorService.shutdown();
        }
    }
}

